package mysql

import (
	"errors"
	"fmt"

	"go.uber.org/zap"

	"bluebell/models"
	"bluebell/pkg/argon"
	"bluebell/pkg/jwt"
)

//调用数据方法
var (
	ErrorUserExits = errors.New("用户已存在")
	ErrorUserNotExits = errors.New("用户不存在")
	ErrorInvalidPassword = errors.New("用户名或密码错误")
)
func CreateUser(user models.User) error {
	if result := DB.Create(&user); result.Error != nil{
		zap.L().Error("创建数据库失败",zap.Error(result.Error))
		return result.Error
	}
	return nil
}

// 查询用户是否存在
// 根据models.User{Username}查询
func ExitUserByUserName(username string) (err error){
	var users models.User
	result := DB.Where(&models.User{UserName: username}).Find(&users)
	if result.RowsAffected > 0 {
		zap.L().Error("用户已存在",zap.Error(result.Error))
		return ErrorUserExits
	}
	if result.Error != nil{
		zap.L().Error("查询失败",zap.Error(result.Error))
		return result.Error
	}
	return nil
}
// 登录逻辑
func Login(loginUser *models.UserLoginForm) (token string,err error){
	var users models.User
	result := DB.Where(&models.User{UserName: loginUser.UserName}).Find(&users)
	if result.Error != nil{
		zap.L().Error("查询失败",zap.Error(result.Error))
		return "",result.Error
	}
	if result.RowsAffected == 0 {
		zap.L().Error("用户不存在",zap.Error(result.Error))
		return "",ErrorUserNotExits
	}
	pas := argon.HasPassWord(loginUser.PassWord)
	if pas == users.PassWord {
		token,err := jwt.GenToken(int64(users.UserID),users.UserName)
		fmt.Println(token,"2222")
		if err != nil{
			zap.L().Error("生成token失败",zap.Error(err))
			return "",err
		}
		return token,nil	
	}else{
		return "",ErrorInvalidPassword
	}

}